package com.example.front.serivce;

import com.alibaba.fastjson.JSONArray;
import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.dto.*;
import com.example.front.entity.*;
import com.example.front.mapper.BoxMapper;
import com.example.interceptor.UserContext;
import com.example.passport.entity.User;
import com.example.passport.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BoxService {
    @Resource
    BoxMapper boxMapper;
    @Resource
    LineService lineService;
    @Resource
    GatewayService gatewayService;
    @Resource
    CategoryService categoryService;
    @Resource
    CraftService craftService;
    @Resource
    UserService userService;
    @Resource
    EquipmentService equipmentService;

    /**
     * 列出盒子
     */
    public ListDto<BoxDto> list(BoxSearchDto condition, Pagination pagination) {
        // 获取总数
        long total = boxMapper.count(condition);
        if (total <= 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }

        pagination.setTotal(total);
        if ( condition.getName() != null || condition.getLineId() != null
                || condition.getCraftId() != null || condition.getGatewayId() != null || condition.getCategoryId() != null
                || condition.getDevAddr() != null){
            pagination.setPage(1);
        }
        // 获取列表并转成Dto
        List<Box> boxList = boxMapper.findAll(condition, pagination);
        List<BoxDto> boxDtoList = boxList.stream().map(box -> {
            BoxDto boxDto = new BoxDto();
            BeanUtils.copyProperties(box, boxDto);
//            boxDto.setEvent(boxEventUserList(boxDto.getId()));
            return boxDto;
        }).collect(Collectors.toList());
        // 获取产线ids
        List<Long> lineIds = boxList.stream().map(Box::getLineId)
                .distinct()
                .collect(Collectors.toList());
        //获取网关ids
        List<Long> gatewayIds = boxList.stream().map(Box::getGatewayId)
                .distinct()
                .collect(Collectors.toList());
        //获取盒子种类ids
        List<Long> categoryIds = boxList.stream().map(Box::getCategoryId)
                .distinct()
                .collect(Collectors.toList());
        System.out.println("==========================>");
        System.out.println(boxList);
        //获取产线信息
        Map<Long, Line> lineMap = lineService.findByIds(lineIds);
        //获取网关信息
        Map<Long, Gateway> gatewayMap = gatewayService.findByIds(gatewayIds);
        //获取盒子种类相关信息
        Map<Long, Category> categoryMap = categoryService.findByIds(categoryIds);

        //设置网关code
        for (BoxDto boxDto : boxDtoList) {
            Line line = lineMap.get(boxDto.getLineId());
            if (line != null) {
                boxDto.setLineName(line.getName());
            }
            Gateway gateway = gatewayMap.get(boxDto.getGatewayId());
            if (gateway != null) {
                boxDto.setGatewayName(gateway.getName());
            }
            Category category = categoryMap.get(boxDto.getCategoryId());
            if (category != null) {
                boxDto.setCategoryName(category.getName());
            }
            System.out.println(boxDto.getCraftId());
            Craft craft = craftService.findById(boxDto.getCraftId(),UserContext.getUser().getTenantId());

            //获取设备名称
            Long equId = boxDto.getEquId();
            if (equId != null){ //不为空获取设备信息
                Equipment equipment = equipmentService.findById(equId);
                if (equipment != null){
                    boxDto.setEquId(equipment.getId());
                    boxDto.setEquName(equipment.getName());
                    boxDto.setEquNum(equipment.getCurrentCoding());
                }
            }

            if (craft != null) {
                boxDto.setCraftName(craft.getName());
            } else {
                boxDto.setCraftName("");
            }
        }
        return new ListDto<>(boxDtoList, pagination);
    }

//    /**
//     * 新增用户和事件的关系表
//     */
//    @Transactional
//    public void boxEventUserCreate(BoxEventUserCreateDto boxEventUserCreateDto, Long boxId) {
//        for (Long userId : boxEventUserCreateDto.getUserId()) {
//            BoxEventUser box = new BoxEventUser();
//            BeanUtils.copyProperties(boxEventUserCreateDto, box);
//            box.setUserId(userId);
//            box.setBoxId(boxId);
//            boxMapper.boxEventUsercreate(box);
//        }
//    }
//
//    /**
//     * 用户和事件的关系表查询
//     */
//    public List<BoxEventUserDto> boxEventUserList(Long boxId) {
//        List<BoxEventUserDto> kk = new ArrayList<>();
//        BoxEventUser a = new BoxEventUser();
//        a.setBoxId(boxId);
//        List<BoxEventUser> b = boxMapper.boxEventUserList(a);
//        if (b.size() == 0) {
//            return null;
//        }
//        Long id = b.get(0).getEventId();
//        Long lastId = b.get(b.size() - 1).getEventId();
//        BoxEventUserDto boxEventUserDto = new BoxEventUserDto();
//        Map<Long, String> map = new HashMap<>();
//        int i = 0;
//        for (BoxEventUser boxEventUser : b) {
//            i++;
//            if (boxEventUser.getEventId() != id || i == b.size()) {
//                if (i == b.size() && boxEventUser.getEventId() == id) {
//                    User user = userService.findById(boxEventUser.getUserId());
//                    map.put(user.getId(), user.getName());
//                }
//                if (b.size() == 1) {
//                    boxEventUserDto.setEventId(boxEventUser.getEventId());
//                    boxEventUserDto.setLevelId(boxEventUser.getLevelId());
//                }
//                if (boxEventUser.getEventId() != id && i == b.size()) {
//                    id = boxEventUser.getEventId();
//                    boxEventUserDto.setUser(map);
//                    kk.add(boxEventUserDto);
//                    boxEventUserDto = new BoxEventUserDto();
//                    map = new HashMap<>();
//                    User user = userService.findById(boxEventUser.getUserId());
//                    map.put(user.getId(), user.getName());
//                    boxEventUserDto.setEventId(boxEventUser.getEventId());
//                    boxEventUserDto.setLevelId(boxEventUser.getLevelId());
//                }
//                id = boxEventUser.getEventId();
//                boxEventUserDto.setUser(map);
//                kk.add(boxEventUserDto);
//                boxEventUserDto = new BoxEventUserDto();
//                map = new HashMap<>();
//            }
//            User user = userService.findById(boxEventUser.getUserId());
//            map.put(user.getId(), user.getName());
//            boxEventUserDto.setEventId(boxEventUser.getEventId());
//            boxEventUserDto.setLevelId(boxEventUser.getLevelId());
//        }
//        return kk;
//    }

//    /**
//     * 创建用户和事件的关系
//     */
//    @Transactional
//    public void createBoxEventUser(@Valid BoxCreateDto boxCreateDto) {
//        BoxDto boxDto = new BoxDto();
//        BeanUtils.copyProperties(boxCreateDto, boxDto);
//        List<BoxEventUserCreateDto> eventList = JSONArray.parseArray(boxCreateDto.getEvent(), BoxEventUserCreateDto.class);
//        if (boxCreateDto.getId() != null && boxCreateDto.getId() != 0) {
//            for (BoxEventUserCreateDto boxEventUserCreateDto : eventList) {
//                if (boxEventUserCreateDto.getLevelId() == null) {
//                    throw new BusinessException("等级不能为空");
//                }
//                if (boxEventUserCreateDto.getUserId() != null) {
//                    boxEventUserCreate(boxEventUserCreateDto, boxCreateDto.getId());
//                }
//            }
//        }
//    }

    /**
     * 创建盒子
     */
    @Transactional
    public void create(@Valid BoxCreateDto boxCreateDto) {
        BoxDto boxDto = new BoxDto();
        BeanUtils.copyProperties(boxCreateDto, boxDto);
        if (boxMapper.findByName(boxCreateDto.getTenantId(), boxDto) != null) {
            throw new BusinessException("名称已存在");
        }
//        if (boxMapper.findByCraftId(boxCreateDto.getTenantId(), boxCreateDto.getCraftId()) != null) {
//            throw new BusinessException("该工艺下已有盒子");
//        }
        if (boxMapper.findByGatewayAddr(boxDto) != null) {
            throw new BusinessException("当前网关序列已存在");
        }
        Box box = new Box();
        boxMapper.create(boxCreateDto);
//        createBoxEventUser(boxCreateDto);

    }

    /**
     * 修改盒子
     */
    @Transactional
    public void update(@Valid BoxCreateDto boxDto) {
//        boxMapper.deleteBoxEventUser(boxDto.getId());

        if ( boxDto.getCraftId() == null && boxDto.getEquId() == null){
            throw new BusinessException("工艺设备请选择一个进行绑定");
        }
//        createBoxEventUser(boxDto);
        Box box = new Box();
        BeanUtils.copyProperties(boxDto, box);
        boxMapper.update(box);

    }

    /**
     * 修改盒子对应的工艺
     */
    public void updateByCraftId(@Valid Box box) {
        box.setTenantId(UserContext.getUser().getTenantId());
        boxMapper.update(box);
    }

    /**
     * 删除盒子
     */
    public void deleteById(long id, long tenantId) {

        if (boxMapper.deleteById(id, tenantId) != 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     * 搜索盒子
     */
    public Box findByGatewayAddr(long tenantId, long id, int addr) {

        BoxDto boxDto = BoxDto.builder().gatewayId(id).devAddr(addr).tenantId(tenantId).build();
        Box box = boxMapper.findByGatewayAddr(boxDto);
        if (box == null) {
            throw new BusinessException("盒子不存在");
        }
        return box;
    }

    /**
     * 搜索盒子
     */
    public Box findById(Long tenantId, Long id) {
        Box box = boxMapper.findById(tenantId, id);
        if (box == null) {
            Box box1 = new Box();
            box1.setName("");
            return box1;
        }
        return box;
    }

    /**
     * 搜索盒子
     */
    public Box findById(Long id) {
        Box box = boxMapper.findByID(id);
        if (box == null) {
            return null;
        }
        return box;
    }

    /**
     * 根据产线搜索盒子
     */
    public long findByLineId(long tenantId, long id) {
        return boxMapper.findByLineId(tenantId, id);
    }

    /**
     * 根据网关搜索盒子
     */
    public long findByGatewayId(long tenantId, long id) {
        return boxMapper.findByGatewayId(tenantId, id);
    }

    /**
     * 根据盒子类型搜索盒子
     */
    public long findByCategoryId(long tenantId, long id) {
        return boxMapper.findByCategoryId(tenantId, id);
    }


}
